package com.xnyzc.lhy.mis.service.impl.cms.menu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xnyzc.lhy.common.component.config.GlobalConfig;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.ListToTreeUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.cms.OaSysMenu;
import com.xnyzc.lhy.mis.entity.cms.OaSysRoleMenu;
import com.xnyzc.lhy.mis.entity.param.cms.OfficeParam;
import com.xnyzc.lhy.mis.entity.result.menu.Menu;
import com.xnyzc.lhy.mis.entity.system.OaSysUser;
import com.xnyzc.lhy.mis.mapper.cms.OaSysMenuMapper;
import com.xnyzc.lhy.mis.mapper.cms.OaSysRoleMenuMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.mis.service.cms.menu.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  目录相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-08-08
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private OaSysUserMapper oaSysUserMapper;

    @Autowired
    private OaSysMenuMapper oaSysMenuMapper;

    @Autowired
    private OaSysRoleMenuMapper oaSysRoleMenuMapper;


    /**
     * 获取菜单列表
     *
     * @return
     */
    @Override
    public Rv getMenuList(OfficeParam officeParam) {
        //查询当前登录
        Long userId=TokenUtil.getTokenUserId();
        OaSysUser user=oaSysUserMapper.selectById(userId);
        if(CheckUtil.objIsEmpty(user)){
            throw PangException.create(EErrorCode.noData);
        }
        //查询全部的目录
        List<OaSysMenu> sourcelist = oaSysMenuMapper.menuRootAllList();
        List<Map<String, Object>> menuMapList =ListToTreeUtil.getMenuList(sourcelist);
        JSONArray resultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(menuMapList)),"id","pId","children");
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 获取菜单详情
     *
     * @return
     */
    @Override
    public Rv getMenuDetail(Menu param) {
        Map<String, Object> map = new HashMap<>(16);
        Menu menu=new Menu();
        if(CheckUtil.objIsNotEmpty(param.getMenuId())) {
            OaSysMenu sysMenu = oaSysMenuMapper.selectById(param.getMenuId());
            if(CheckUtil.objIsEmpty(sysMenu)){
                throw PangException.create(EErrorCode.noData);
            }
            OaSysMenu parentMenu = oaSysMenuMapper.selectById(sysMenu.getParentId());
            menu.setParentName(parentMenu.getName());
            menu.setHref(sysMenu.getHref());
            menu.setIcon(sysMenu.getIcon());
            menu.setIsShow(sysMenu.getIsShow());
            menu.setMenuId(sysMenu.getMenuId());
            menu.setName(sysMenu.getName());
            menu.setParentId(sysMenu.getParentId());
            menu.setParentIds(sysMenu.getParentIds());
            menu.setPermission(sysMenu.getPermission());
            menu.setSort(sysMenu.getSort());
            menu.setTarget(sysMenu.getTarget());
            menu.setVersion(sysMenu.getVersion());
            //查询操作人
            OaSysUser updateUser = oaSysUserMapper.selectById(sysMenu.getUpdateUser());
            menu.setUpdateUser(updateUser.getName());
        }
        List<OaSysMenu> sourcelist = oaSysMenuMapper.menuAllList();
        List<Map<String, Object>> menuMapList =ListToTreeUtil.getMenuList(sourcelist);
        JSONArray menuTreeList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(menuMapList)),"id","pId","children");
        map.put("menu",menu);
        map.put("menuTreeList",menuTreeList);
        return Rv.wrap(EErrorCode.success, map);
    }

    /**
     * 获取拉取目录结构列表
     * @param currentId 当前菜单id
     * @return
     */
    @Override
    public Rv getMenuTreeData(Long currentId) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<OaSysMenu> list = oaSysMenuMapper.menuAllList();
        for (int i=0; i<list.size(); i++){
            OaSysMenu e = list.get(i);
            if (CheckUtil.objIsEmpty(currentId) || (currentId!=null && !currentId.equals(e.getMenuId()) && e.getParentIds().indexOf(","+currentId+",")==-1)){
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getMenuId());
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
        JSONArray resultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(mapList)),"id","pId","children");
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 新增、修改菜单
     *
     * @return
     */
    @Override
    public Rv getUpdateMenu(Menu menu) {
        Long userId=TokenUtil.getTokenUserId();
        String tag=TokenUtil.getTag();
        List<String> roleList=TokenUtil.getRoleDataScope();
        if(!roleList.contains(GlobalConfig.DATA_SCOPE_ALL)){
            throw PangException.create(EErrorCode.permissionsErr);
        }
        Date date=new Date();
        String oldParentIds ="";
        String newParentIds ="";
        Long id=0L;
        // 新增
        if (CheckUtil.objIsEmpty(menu.getMenuId())){
            id=IDUtil.nextId();
            OaSysMenu updateMenu=new OaSysMenu();
            // 选择的实体
            OaSysMenu newMenu=oaSysMenuMapper.selectById(menu.getNewMenuId());
            newParentIds=newMenu.getParentIds();
            oldParentIds = newMenu.getParentIds();
            updateMenu.setMenuId(id);
            updateMenu.setParentId(String.valueOf(newMenu.getMenuId()));
            updateMenu.setParentIds(newMenu.getParentIds()+newMenu.getMenuId()+",");
            updateMenu.setHref(menu.getHref());
            updateMenu.setIcon(menu.getIcon());
            updateMenu.setIsShow(menu.getIsShow());
            updateMenu.setName(menu.getName());
            updateMenu.setSort(menu.getSort());
            updateMenu.setPermission(menu.getPermission());
            updateMenu.setTarget(menu.getTarget());
            updateMenu.setCreateTime(date);
            updateMenu.setCreateUser(userId);
            updateMenu.setUpdateUser(userId);
            updateMenu.setUpdateTime(date);
            updateMenu.setTag(tag);
            oaSysMenuMapper.insert(updateMenu);
        }
        // 修改
        else{
            id=menu.getMenuId();
            // 需修改的实体
            OaSysMenu updateMenu=oaSysMenuMapper.selectById(menu.getMenuId());
            oldParentIds = updateMenu.getParentIds();
            // 选择的实体
            OaSysMenu newMenu=oaSysMenuMapper.selectById(menu.getNewMenuId());
            if(!String.valueOf(id).equals(String.valueOf(menu.getNewMenuId()))){
                updateMenu.setParentId(String.valueOf(newMenu.getMenuId()));
                updateMenu.setParentIds(newMenu.getParentIds()+newMenu.getMenuId()+",");
            }
            newParentIds=updateMenu.getParentIds();
            updateMenu.setHref(menu.getHref());
            updateMenu.setIcon(menu.getIcon());
            updateMenu.setIsShow(menu.getIsShow());
            updateMenu.setName(menu.getName());
            updateMenu.setSort(menu.getSort());
            updateMenu.setTarget(menu.getTarget());
            updateMenu.setUpdateUser(userId);
            updateMenu.setPermission(menu.getPermission());
            updateMenu.setUpdateTime(date);
            updateMenu.setTag(tag);
            oaSysMenuMapper.updateById(updateMenu);
        }
        // 更新子节点 parentIds
        if(!String.valueOf(id).equals(String.valueOf(menu.getNewMenuId()))){
            QueryWrapper<OaSysMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(OaSysMenu.PARENT_IDS, id);
            List<OaSysMenu> likeMenu = oaSysMenuMapper.selectList(queryWrapper);
            for(OaSysMenu l:likeMenu){
                l.setParentIds(l.getParentIds().replace(oldParentIds,newParentIds));
                l.setUpdateUser(userId);
                l.setUpdateTime(date);
                oaSysMenuMapper.updateById(l);
            }
        }
        return Rv.wrap(EErrorCode.updateSuccess);
    }

    /**
     * 删除菜单
     *
     * @return
     */
    @Override
    public Rv getDeleteMenu(Menu menu) {
        List<String> roleList=TokenUtil.getRoleDataScope();
        if(!roleList.contains(GlobalConfig.DATA_SCOPE_ALL)){
            throw PangException.create(EErrorCode.permissionsErr);
        }
        List<Long> allMenuIdList=new ArrayList<>();
        QueryWrapper<OaSysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysMenu.MENU_ID, menu.getMenuId()).or().like(OaSysMenu.PARENT_IDS,menu.getMenuId());
        List<OaSysMenu> allMenuList=oaSysMenuMapper.selectList(queryWrapper);
        if(!allMenuList.isEmpty()){
            for(OaSysMenu all:allMenuList){
                allMenuIdList.add(all.getMenuId());
            }
        }
        // 删除
        QueryWrapper<OaSysMenu> deleteQueryWrapper = new QueryWrapper<>();
        deleteQueryWrapper.eq(OaSysMenu.MENU_ID, menu.getMenuId()).or().like(OaSysMenu.PARENT_IDS,menu.getMenuId());
        oaSysMenuMapper.delete(deleteQueryWrapper);

        // 删除关联
        QueryWrapper<OaSysRoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.in(OaSysRoleMenu.MENU_ID, allMenuIdList);
        oaSysRoleMenuMapper.delete(roleMenuQueryWrapper);

        return Rv.wrap(EErrorCode.deleteSuccess);
    }

}
